#include "token.h"
#include "expression.h"
#include <stdlib.h>
#include <string.h>

token* token_create( int type, code *cd, uint8 *end, void *attr, struct _exp_tree *ppcond )
{
    token *tk;
    tk = (token *)malloc( sizeof(token) );
    init_life( tk );
    tk->file = cd->file;
    tk->line = cd->line;
    tk->attr = attr;
    tk->type = type;
    tk->ppcond = ppcond;
    tk->name = (char *)malloc( end - cd->code_buf + 1 );
    strncpy( tk->name, (char*)cd->code_buf, end-cd->code_buf );
    tk->name[end - cd->code_buf ] = 0;
    if( ppcond )
        add_ref( ppcond );
    return tk;
}

token* token_create_raw( int type, const char *name, char *file, int line, void *attr, struct _exp_tree *ppcond )
{
    token *tk;
    tk = (token *)malloc( sizeof(token) );
    init_life( tk );
    tk->file = file;
    tk->line = line;
    tk->attr = attr;
    tk->type = type;
    tk->ppcond = ppcond;
    tk->name = (char *)malloc( strlen(name) + 1 );
    strcpy( tk->name, name );
    if( ppcond )
        add_ref( ppcond );
    return tk;
}

int token_release( token *tk )
{
    int ref = release( tk );
    if( ref <= 0 )
    {
        if( tk->ppcond )
            exp_tree_release( tk->ppcond );
        if( tk->attr )
            free( tk->attr );
        if( tk->name )
            free( tk->name );
        free( tk );
    }
    return ref;
}

int tkcmp( token *t1, token *t2 )
{
    return strcmp( t1->name, t2->name );
}
